package com.itmk.web.sys_class.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itmk.utils.ResultUtils;
import com.itmk.utils.ResultVo;
import com.itmk.web.sys_class.entity.ClassPage;
import com.itmk.web.sys_class.entity.SysClass;
import com.itmk.web.sys_class.service.SysClassService;
import com.itmk.web.sys_major.entity.Major;
import com.itmk.web.sys_major.entity.SelectMajor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author java实战基地
 * @since 2023-10-08
 */
@RestController
@RequestMapping("/api/sysClass")
public class SysClassController {
    @Autowired
    private SysClassService sysClassService;

    //新增
    @PostMapping
    public ResultVo add(@RequestBody SysClass sysClass){
        if(sysClassService.save(sysClass)){
            return ResultUtils.success("新增成功");
        }
        return ResultUtils.error("新增失败!");
    }


    //编辑
    @PutMapping
    public ResultVo edit(@RequestBody SysClass sysClass){
        if(sysClassService.updateById(sysClass)){
            return ResultUtils.success("编辑成功");
        }
        return ResultUtils.error("编辑失败!");
    }

    //删除
    @DeleteMapping("/{classId}")
    public ResultVo delete(@PathVariable("classId") Integer classId){
        if(sysClassService.removeById(classId)){
            return ResultUtils.success("删除成功");
        }
        return ResultUtils.error("删除失败!");
    }

    //列表查询
    @GetMapping("/list")
    public ResultVo getList(ClassPage parm){
        IPage<SysClass> list = sysClassService.getList(parm);
        return ResultUtils.success("查询成功",list);
    }

    //班级下拉数据
    @GetMapping("/select")
    public ResultVo select(){
        List<SysClass> list = sysClassService.list();
        List<SelectMajor> selectMajors = new ArrayList<>();
        Optional.ofNullable(list).orElse(new ArrayList<>())
                .stream()
                .forEach(item ->{
                    SelectMajor major = new SelectMajor();
                    major.setLabel(item.getClassName());
                    major.setValue(item.getClassId());
                    selectMajors.add(major);
                });
        return ResultUtils.success("查询成功",selectMajors);
    }
}

